<style lang="scss" scoped="">
  .content_left{
    width: 100%;
    height: 100%;
    // box-shadow: 2px 2px 3px rgba(68,68,68,0.1),-2px -2px 3px rgba(68,68,68,0.1);
    background-color: white;
    padding-left: 10px;
    padding-right: 10px;
    float: left;
    overflow-y:hidden;

    .left_header{
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    };
    .entry{
      padding-bottom: 3px;
      padding-top: 3px;
      font-size: 14px;
      overflow: hidden;
      text-overflow:ellipsis;
      white-space: nowrap;
      &.act{
        background-color: rgb(240,240,240);
      }
    }

  }

  .content_right {
    width: 100%;
    height: 100%;
    // box-shadow: 2px 2px 3px rgba(68, 68, 68, 0.1), -2px -2px 3px rgba(68, 68, 68, 0.1);
    background-color: white;
    float: right;

  }
  .info_left{
    margin-left: 10px;
    z-index: 3000;
  }

  .info_right{
    padding-right: 10px;

    display: flex;
    align-items:center;
    justify-content:flex-end;
    flex-wrap: nowrap;
    .show_tab{
      font-size: 13px;
      z-index: 10;
      &.act{
        color:#00c853;
        border-bottom: 1px solid #00c853;
      }
    };
    .show_tab:hover{
      cursor: pointer;
    }
  }
  // .info_right /deep/  div{
  //   border:none;
  //    z-index: 3000;
  // }



  .quest_content{
    width: 100%;
    height: 100%;
    padding-left:10px;
    padding-right:10px;
    overflow-y: auto;
    .qheader{
      font-size: 20px;
      height: 58px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-left: 5px;
      border-bottom: 1px solid rgb(240,240,240);
    };
    .gcontent{
      font-size: 16px;
      padding:10px;
      margin-bottom: 10px;
      .des{
        margin-top: 5px;
        margin-bottom: 5px;
        div{
          height: 55px;
          width: 100%;
          display: flex;
          align-items: center;
          .input{

            width: 100px;
            flex:100;
          }
        }
      };

    }
  }


</style>
<template>
  <mpage>
    <mheader/>
    <minfo>
      <div slot="left" class="info_left">
      </div>
      <div slot="right" style="z-index: 5000" class="info_right">


        <Tooltip content="取消编辑" placement="bottom-end" v-show="ifedit" >
          <Button type="primary" shape="circle" icon="ios-eye"  @click="ifedit=!ifedit"></Button>
        </Tooltip>
        <Tooltip content="开启编辑" placement="bottom-end" v-show="!ifedit" style="margin-right: 10px">
          <Button type="primary" shape="circle" icon="ios-create"  @click="ifedit=!ifedit"></Button>
        </Tooltip>
        <div v-show="ifedit" style="margin-left: 10px">
          <Tooltip content="保存操作" placement="bottom-end"  >
            <Button type="primary" shape="circle" icon="md-sync" @click="save_entry()"></Button>
          </Tooltip>
          <Tooltip content="删除" placement="bottom-end"  style="margin-left: 3px" >
            <Button type="primary" shape="circle" icon="md-trash" @click="deleteEntry()"></Button>
          </Tooltip>
        </div>



        <!--<Button type="primary" style="width: auto" size="small" @click="ifedit=!ifedit">{{!ifedit?'启动编辑':'取消编辑'}}</Button>-->
        <!--<Dropdown placement="bottom-end" >-->
          <!--<a href="javascript:void(0)">-->

            <!--<Icon type="ios-arrow-down" color="#1b5e20"></Icon>-->
          <!--</a>-->
          <!--<DropdownMenu slot="list">-->
            <!--<DropdownItem name="save">保存条目</DropdownItem>-->
            <!--<DropdownItem name="delete">删除条目</DropdownItem>-->

          <!--</DropdownMenu>-->
        <!--</Dropdown>-->
      </div>

    </minfo>
    <mcontainer>
      <div style="height: 100%;width: 100%">
        <Split v-model="split1" :min="0.08" max="500px">
            <div slot="left" class="content_left">
                <div class="left_header">
                  知识目录 <Icon type="md-add" style="margin-left: 10px"  color="#00c853" @click="add_entry()"/>
                </div>
                <vue-scroll :ops="scrollOps">
                  <template v-if="this.entry_list.length>0">
                    <div v-for="(item,index) in entry_list" @click="selectEntry(item,index)" class="entry" :class="{act:item.id==now_entry_id}" >
                      {{item.key_question}}
                    </div>

                  </template>
                </vue-scroll>

            </div>
            <div slot="right" class="content_right">
               <template v-if="entry_list.length>0">




               <div  class="quest_content">
                 <div class="qheader" style="border-bottom: 1px solid rgb(210,210,210);">
                   <input type="text" v-model="entry_list[now_entry_index].key_question"
                   style="border:none;width: 100%;font-size: 24px;color:rgb(80,80,80);outline:none" placeholder="请输入问题"/>



                 </div>
                 <div class="gcontent">

                 </div>
                 <div class="qheader" >
                   <div>问题描述<span style="font-size: 13px;margin-left: 15px;color:#bbb">尽量对问题进行清晰、多样化的描述哦</span></div>  <Icon type="md-add" style="float:right" color="#00c853" v-show="ifedit" @click="addQuestion"/>
                 </div>
                 <div class="gcontent">
                   <template v-if="quest_list.length>0">
                     <div class="des" v-for="(item,index) in quest_list">
                       描述{{index+1}}:
                       <div>
                         <Input v-model="quest_list[index]" placeholder="请输入问题描述" class="input" :disabled="!ifedit" size="large"/>
                         <Icon type="md-remove" style="margin-left: 10px" color="red"  v-show="ifedit" @click="quest_list.splice(index,1)"/>
                       </div>

                     </div>
                   </template>
                   <template v-else>
                     <div style="color: rgb(180,180,180);">缺乏问题描述，请开启编辑模式后，点击加号补充 </div>

                   </template>



                 </div>
                 <div class="qheader" >
                   <div>知识内容<span style="font-size: 13px;margin-left: 15px;color:#bbb">知识内容文本</span></div>
                 </div>
                 <div class="gcontent">
                   <mavonEditor ref=md v-model="content_value"  :boxShadow="false"  :editable="ifedit"  :toolbarsFlag="ifedit" :subfield="ifedit" :defaultOpen="ifedit?'edit':'preview'" :toolbars="toolbars" :ishljs = "true"
                                :shortCut="false"  fontSize="12px"   style="height: 100%;" codeStyle="atelier-heath-dark"
                   @imgAdd="imgAdd" @imgDel="imgDel"></mavonEditor>

                 </div>
                 <div class="qheader" >
                   <div>附件<span style="font-size: 13px;margin-left: 15px;color:#bbb">当前已添加附件数量为{{fileList.length}}</span></div>
                 </div>
                 <div class="gcontent">
                   <!-- <Upload  action="http://localhost:8083/uploadImage"
                            :on-error="uploadError"
                            :on-success="fileOnSuccess">
                     <Button icon="ios-cloud-upload-outline">点击上传附件</Button>
                   </Upload> -->
                    <file_uploader :fileList.sync="fileList" :action="fileUpLoadAction" :ifEdit="ifedit"></file_uploader>
                 </div>

               </div>

               </template>
               <template v-else="">
                 <div style="font-size: 30px;text-align: center;padding-top: 80px">
                   <div>暂无数据，请新建</div>
                 </div>
               </template>
            </div>
        </Split>

      </div>

        <Modal
          v-model="confirm_save_model"
          title="新建知识尚未保存"
          @on-ok="save_entry()"
          @on-cancel="dont_save_entry">
          <p>你新建的知识尚未保存，是否保存？如取消会清除当前新建知识所有内容！</p>
        </Modal>


    </mcontainer>

  </mpage>




</template>

<script>
  import mpage from "../comp_chatter/mpage"
  import mheader from "../comp_chatter/mheader"
  import minfo from "../comp_chatter/minfo"
  import mcontainer from '../comp_chatter/mcontainer'
  import file_uploader from "./file_uploader"
  import { mavonEditor } from 'mavon-editor'
  import 'mavon-editor/dist/css/index.css'
  import Axios from 'axios'
import ajax from "../ajax_util"
    var md_img_g={}
    var resp_img_names_g=[];
    var now_if_create_g=false;
    export default {
      name: 'know_edit',
      components: {
        mheader,mpage,minfo,mcontainer,mavonEditor,file_uploader
      },
      props:{

      },
    data() {
      return {
         split1: 0.2,
        ifedit:false,
        now_entry_id:0,
        now_entry_index:0,
        toolbars:toolbars_g,

        confirm_save_model:false,
        entry_list:[
          {
            "id":1,
            "key_question":"paas"
          }
        ],
        quest_list:[
          "fdfd","fdfdfdfd"
        ],
        content_value:"### demo \n ![image](img0)  ![image](img1)",
        fileList:[

        ],
        fileUpLoadAction:"",
        img_dict:{},
        scrollOps:{
          bar: {
              showDelay: 500,
              onlyShowBarOnScroll: true,
              keepShow: false,
              background: '#c1c1c1',
              opacity: 1,
              hoverStyle: false,
              specifyBorderRadius: false,
              minSize: false,
              size: '2px',
              disable: false,
            },
            rail:{
               gutterOfSide:0
            }
        }
      }
    },
    mounted() {
      //v-note-wrapper
      var eles=document.getElementsByClassName("v-show-content")[0];
      eles.style.backgroundColor="white";
      var eles2=document.getElementsByClassName("v-note-wrapper")[0];

      eles2.style.zIndex=10;


      // console.log(this.$route.params)

      this.get_entrys();
      this.fileUpLoadAction=this.CONFIG.url_know+"/kentry/uploadfile/";//文件上传路径设置
//      this.get_speci_entry()
    },
    methods: {

      uploadError(error, file){
        console.log(error)
      },
      get_entrys(){
        let subject_id=this.$route.params.id
        var url=this.CONFIG.url_know+'/kentrys/'+subject_id;
        Axios.get(url)
          .then(response => {
//              console.log("------get_entrys---------",response.data)
              this.entry_list=response.data;
              if(this.entry_list.length>0){
                this.now_entry_index=0;
                this.now_entry_id=this.entry_list[this.now_entry_index]["id"];

                this.get_speci_entry(this.now_entry_id)
              }



          })
          .catch(error => {
            console.log("----------get_entrys error------",error.response);
          });
      },
      get_speci_entry(entry_id){
        var that=this;

        var url=this.CONFIG.url_know+'/kentry/'+entry_id;
        // console.log(url)
        Axios.get(url)
          .then(response => {
           // console.log("get_speci_entry",response.data)
            this.quest_list=response.data["other_questions"];
            this.content_value=response.data["content"];
            this.fileList=response.data["files"];
            let images=response.data["images"]
            resp_img_names_g=[]
            this.$nextTick(() => {
              // $vm.$imgUpdateByUrl 详情见本页末尾
              for(var i in images){
                resp_img_names_g.push(images[i]["name"])

                var img_url=this.CONFIG.url_know+"/images/"+images[i]["name"];
                // console.log(img_url)
//          console.log(uu)
////          this.$refs.md.$img2Url(filename, uu);
//          this.$refs.md.$imgUpdateByUrl(filename, uu)
                this.$refs.md.$imgUpdateByUrl(images[i]["name"], img_url)
              }



            })


          })
          .catch(error => {
            console.log(1111,error.response);
          });



      },

      save_entry(){
          console.log("--save_entry--------")
          var that=this;
          var entry={
            subject_id:this.$route.params.id,
            key_question:this.entry_list[this.now_entry_index]["key_question"],
            other_questions:this.quest_list,
            content:this.content_value,
            files:this.fileList

          };
          var img_upload_url=that.CONFIG.url_know+'/uploadKentryImages';
          if(now_if_create_g){//说明是新增

            var formdata = new FormData();
            var img_arr=[]
            var matched_arr =  this.content_value.match(/\!\[.*?]\((.*?)\)/g);
            for(var i in matched_arr){
              var img_name=/\!\[.*?]\((.*?)\)/g.exec(matched_arr[i])[1];
              img_arr.push({
                name:img_name
              })
              formdata.append(img_name,md_img_g[img_name])
          }
            Axios({
              url: img_upload_url,
              method: 'post',
              data: formdata,
              headers: { 'Content-Type': 'multipart/form-data' },
            }).then(response => {
                entry['images']=img_arr

                var url=this.CONFIG.url_know+'/kentry';
                Axios.post(url,entry)
                .then(response => {
                  now_if_create_g=false;
                  that.$Message.info('知识条目已成功保存');
                  that.get_entrys();
                })
                .catch(error => {
                  console.log(1111,error.response);
                });
            })

          }else{//说明是修改，主要是图片修改方式要注意
            var img_arr=[]
            var matched_arr =  this.content_value.match(/\!\[.*?]\((.*?)\)/g);
            var imgs_unchange=[];
            var formdata = new FormData();
            for(var i in matched_arr){
              var img_name=/\!\[.*?]\((.*?)\)/g.exec(matched_arr[i])[1];
              if (resp_img_names_g.indexOf(img_name)>=0){//说明这个图片是不用修改的
                imgs_unchange.push(img_name)

              }else{//说明这个图片是新增的
                formdata.append(img_name,md_img_g[img_name])

              }
              img_arr.push({
                name:img_name
              })

            }

          Axios({
            url: img_upload_url,
            method: 'post',
            data: formdata,
            headers: { 'Content-Type': 'multipart/form-data' },
          }).then(response => {
            entry['images']=img_arr;
            entry['imgs_unchange']=imgs_unchange;
            entry["id"]=this.now_entry_id;
            var url=this.CONFIG.url_know+'/kentry';
            Axios.put(url,entry).then(response => {
              now_if_create_g=false;
              this.$Message.info('知识条目已成功修改');
              this.get_entrys();

            }) .catch(error => {
              console.log(1111,error.response);
            });
          })



        }


      },

      deleteEntry(){
        console.log("deleteEntry")
        var id=this.now_entry_id
        var url=this.CONFIG.url_know+'/kentry/'+id;
        Axios.delete(url)
          .then(response => {
            now_if_create_g=false;
            this.$Message.info('知识条目已删除');
            this.get_entrys();

          })
          .catch(error => {
            console.log("know edit 网络异常： ",error.response);
          });
      },
      dont_save_entry(){
        for (var i in  this.entry_list){
          if(this.entry_list[i].id==this.now_entry_id){
            this.now_entry_index=i
          }
        }
        this.entry_list.splice(this.entry_list.length-1,1);
        now_if_create_g=false;

      },
      imgAdd(filename,imgfile){

        let img_name=guid();
        this.$refs.md.$img2Url(filename,img_name);//md中图片改名
        this.$refs.md.$imgUpdateByUrl(img_name, imgfile.miniurl);//md中图片改名后会对应不上图片文件，这里是把图片文件重新给对应图片
        md_img_g[img_name]=imgfile;//记录图片，后面上传用
      },
      imgDel(filename){
        console.log('------------imgDel------------',filename)
      },
      selectEntry(item,index){
//        console.log("selectEntry",item.id,index)
        if(item.id==this.now_entry_id){
          return
        }
        this.now_entry_id=item.id;
        this.get_speci_entry(item.id);
        if(!now_if_create_g){//说明上一步没有在新建，可以直接切换

          this.now_entry_index=index
        }else{
          this.confirm_save_model=true
        }


      },
      add_entry(){

        if(now_if_create_g){
          this.$Message.warning('请保存当前新建知识条目后再增加');
          return
        }
        this.fileUpLoadAction=this.CONFIG.url_know+"/kentry/uploadfile";//附件上传路径设置
        this.ifedit=true;
        this.quest_list=[];
        this.fileList=[];
        this.content_value="";
        this.entry_list.push({
          "key_question":"新建知识-未命名",
          "id":-1
        })
        this.now_entry_id=-1
        this.now_entry_index=this.entry_list.length-1
        now_if_create_g=true;
      },
      addQuestion(){
        this.quest_list.push("")
      },

    },

  }
  function guid() {
    function S4() {
      return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    }
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
  }
  var toolbars_g={
      bold: true, // 粗体
      italic: true, // 斜体
      header: true, // 标题
      underline: true, // 下划线
      strikethrough: false, // 中划线
      mark: true, // 标记
      superscript: true, // 上角标
      subscript: true, // 下角标
      quote: true, // 引用
      ol: true, // 有序列表
      ul: true, // 无序列表
      link: true, // 链接
      imagelink: true, // 图片链接
      code: true, // code
      table: true, // 表格
      fullscreen: true, // 全屏编辑
      readmodel: false, // 沉浸式阅读
      htmlcode: false, // 展示html源码
      help: true, // 帮助
      /* 1.3.5 */
      undo: true, // 上一步
      redo: true, // 下一步
      trash: false, // 清空
      save: false, // 保存（触发events中的save事件）
      /* 1.4.2 */
      navigation: true, // 导航目录
      /* 2.1.8 */
      alignleft: true, // 左对齐
      aligncenter: true, // 居中
      alignright: true, // 右对齐
      /* 2.2.1 */
      subfield: false, // 单双栏模式
      preview: true, // 预览
  }
</script>
